package com.zyj.mds.config;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.Map;

@Configuration
public class MultiDataSourceConfig {

    @Bean("dsProperties1")
    @ConfigurationProperties(prefix = "spring.datasource.db1")
    public DataSourceProperties dsProperties1() {
        return new DataSourceProperties();
    }

    @Bean(name = "dataSource1")
    public DataSource dataSource1(@Qualifier("dsProperties1") DataSourceProperties dsProperties1) {
        return dsProperties1.initializeDataSourceBuilder().type(HikariDataSource.class).build();
    }

    @Bean("dsProperties2")
    @ConfigurationProperties(prefix = "spring.datasource.db2")
    public DataSourceProperties dsProperties2() {
        return new DataSourceProperties();
    }

    @Bean(name = "dataSource2")
    public DataSource dataSource2(@Qualifier("dsProperties2") DataSourceProperties dsProperties2) {
        return dsProperties2.initializeDataSourceBuilder().type(HikariDataSource.class).build();
    }

    @Primary
    @Bean("dynamicDataSource")
    public DynamicDataSource dynamicDataSource(@Qualifier("dataSource1") DataSource dataSource1,
                                               @Qualifier("dataSource2") DataSource dataSource2) {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        //1. 设置默认数据源
        dynamicDataSource.setDefaultTargetDataSource(dataSource1);
        //2. 存入一个数据源的map
        Map<Object, Object> dataSourceMap = Map.of(
                DataSourceEnum.DB1, dataSource1,
                DataSourceEnum.DB2, dataSource2
        );
        dynamicDataSource.setTargetDataSources(dataSourceMap);
        return dynamicDataSource;
    }

}
